package com.xx.job.filter;

import com.alibaba.fastjson.JSONObject;
import com.xx.job.entity.system.SysMenu;
import com.xx.job.entity.system.SysUser;
import com.xx.job.service.system.SysMenuService;
import com.xx.job.service.system.SysRoleMenuService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@Component
public class InterfaceAuthInterceptor  implements HandlerInterceptor {

    @Autowired
    private SysRoleMenuService sysRoleMenuService;
    @Autowired
    private SysMenuService SysMenuService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)throws Exception{
        String method = request.getMethod();
        if(method.equals("OPTIONS")){
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
        }
        String path = request.getRequestURI();
        path = this.getPath(path);
        response.setCharacterEncoding("utf-8");
        HttpSession session = request.getSession();
        SysUser sysUser = (SysUser) session.getAttribute("sysUser");
        Long roleId = sysUser.getRoleId();
        List<Long> menuIds = sysRoleMenuService.selectByRoleId(roleId);
        List<String> types = new ArrayList<>();
        types.add("A");
        List<SysMenu> menuList = SysMenuService.getMenuList(roleId, types,path,method);
        if(menuList != null && menuList.size() > 0){
            return true;
        }
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        try{
            JSONObject json = new JSONObject();
            json.put("msg","没有接口权限");
            json.put("code",403);
            response.getWriter().append(json.toJSONString());
            System.out.println("认证失败，没有接口权限");
        }catch (Exception e){
            e.printStackTrace();
            response.sendError(500);
            return false;
        }

        return false;
    }

    public String getPath(String path){
        int last = path.lastIndexOf("/");
        String substring = path.substring(last + 1 , path.length());
        String uri = path.substring(0, last + 1);
        String[] ids = substring.split(",");
        if(ids != null && ids.length != 0){
            if(ids[0].matches("\\d+")){
                return uri + ":id";
            }

        }
        return path;
    }
}
